package com.zzr.demo.redis.service.impl;

import com.zzr.demo.redis.service.BlockMQService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author: xiaomi
 * @date: 2021/10/8
 * @description: 实现带阻塞的MQ
 * 需要额外增加消费者（这里使用异步任务）：
 */
@Service
@Slf4j
public class BlockMQServiceImpl implements BlockMQService {

    final String BLOCK_MQ_KEY = "block::mq";
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean addMessage(String msg) {
        ListOperations<String, String> opsForList = stringRedisTemplate.opsForList();
        Long num = opsForList.leftPush(BLOCK_MQ_KEY, msg);
        return num > 0;
    }

    @Override
    public String getMessageWithBlock() {
        ListOperations<String, String> opsForList = stringRedisTemplate.opsForList();
        //BRPOP
        String str = opsForList.rightPop(BLOCK_MQ_KEY, 0, TimeUnit.HOURS);
        return str;
    }

    @Override
    public long size() {
        ListOperations<String, String> opsForList = stringRedisTemplate.opsForList();
        return opsForList.size(BLOCK_MQ_KEY);
    }
}
